/*
 * COPYRIGHT(c) SK telecom 2009
 * This software is the proprietary information of SK telecom.
 *
 * Revision History
 * Author     Date          Description
 * --------   ----------    ------------------
 * 홍길동            2009. 4. 29.    Description
 *
 */
package com.tisotry.admin.adminmgr.auth.persistence.dao;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import com.ibatis.dao.client.DaoException;
import com.ibatis.dao.client.DaoManager;
import com.ibatis.dao.client.template.SqlMapDaoTemplate;
import com.omp.admin.adminmgr.auth.model.AdminMember;
import com.omp.commons.paging.PageNavigator;
import com.omp.commons.paging.PageResultList;
import com.omp.commons.utils.CipherAES;
import com.tistory.admin.common.log.OmpLogger;

/**
 * TODO 클래스 설명을 입력해 주세요.
 * <p/>
 * 상세한 설명을 입력해 주세요.
 * 
 * @author 홍길동
 * @version 0.1
 */
public class AdminMemberDAOImpl extends SqlMapDaoTemplate implements AdminMemberDAO {

	public AdminMemberDAOImpl(DaoManager daoManager) {
		super(daoManager);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.omp.admin.adminmgr.auth.persistence.dao.AdminMemberDAO#adminMemberCreate(com.omp.admin.adminmgr.auth.model
	 * .AdminMember)
	 */
	@Override
	public AdminMember adminMemberCreate(AdminMember adminMem) {
		AdminMember model = new AdminMember();

		try {

			adminMem.setPassword(getDigestHash(adminMem.getPassword()));

			model = (AdminMember) insert("AdminMember.adminMemberCreate", adminMem);
		} catch (Exception e) {
			OmpLogger.error(e.getMessage(), e);
		}
		return model;
	}

	@Override
	public int adminMemberDelete(String id) {

		return delete("AdminMember.adminMemberDelete", id);
	}

	@Override
	public int adminMemberLoginDateUpdate(String id) {

		return update("AdminMember.adminMemberLoginDateUpdate", id);
	}

	@Override
	public int adminMemberUpdate(AdminMember adminMem) {

		int result = 0;
		try {
			// 비밀번호변경이 없는 경우
			if (adminMem.getPassword().equals("0000000")) {
				adminMem.setPassword(CipherAES.decrypt(adminMem.getCipherPassword()));
				// 비밀번호 변경이 없는경우 PWD_UPD_DTS 컬럼값 을 "" 공백으로 넣는다.
			} else {
				OmpLogger.info("N" + CipherAES.encrypt(adminMem.getPassword()));
				// 암호화 해서 저장
				adminMem.setPassword(getDigestHash(adminMem.getPassword()));
			}

			result = update("AdminMember.adminMemberUpdate", adminMem);
		} catch (Exception e) {
			OmpLogger.error(e.getMessage(), e);
		}
		return result;

	}

	@Override
	public AdminMember adminMemberFind(String id) {
		AdminMember model = new AdminMember();
		try {
			model = (AdminMember) queryForObject("AdminMember.adminMemberFind", id);
			if (model != null) {
				// 비밀번호암호화
				model.setCipherPassword(CipherAES.encrypt(model.getPassword()));
				model.setPassword("0000000"); // 보이기용

				OmpLogger.debug("복호화 후 getPassword() ===========>" + CipherAES.decrypt(model.getCipherPassword()));
			}
		} catch (Exception e) {
			OmpLogger.error(e.getMessage(), e);
		}
		return model;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.omp.admin.adminmgr.auth.persistence.dao.AdminMemberDAO#adminMemberList()
	 */
	@Override
	public PageResultList adminMemberList(PageNavigator pageNavi, AdminMember adminMem) {

		HashMap map = new HashMap();
		map.put("pageNavi", pageNavi);
		map.put("AdminMember", adminMem);
		List adminMemList = queryForList("AdminMember.adminMemberList", map);

		int totCnt = Integer.parseInt((String) queryForObject("AdminMember.totalCounts", map));
		PageResultList pList = new PageResultList(adminMemList);
		pList.setTotalSize(totCnt);

		return pList;
	}

	/**
	 * @deprecated
	 */
	@Deprecated
	@Override
	public List adminAuthMgrList(String mgrId) {

		return queryForList("AdminMember.adminAuthMgrList", mgrId);
	}

	@Override
	public int adminAuthMgrInsert(String mgrId, String menuId, String loginId) {
		HashMap map = new HashMap<String, String>();
		map.put("mgrId", mgrId);
		map.put("menuId", menuId);
		map.put("loginId", loginId);
		Object obj = insert("AdminMember.adminAuthMgrUpdate", map);
		OmpLogger.debug("###OBJ=>" + obj);
		return 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.omp.admin.adminmgr.auth.persistence.dao.AdminMemberDAO#adminAuthMgrDelete(java.lang.String)
	 */
	@Override
	public int adminAuthMgrDelete(String mgrId) {
		int cnt = delete("AdminMember.adminAuthMgrDelete", mgrId.toString());
		return cnt;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.omp.admin.adminmgr.auth.persistence.dao.AdminMemberDAO#adminLogin(java.lang.String, java.lang.String)
	 */
	@Override
	public AdminMember adminLogin(AdminMember adminMem) {
		adminMem.setPassword(getDigestHash(adminMem.getPassword()));
		return (AdminMember) queryForObject("AdminMember.adminLogin", adminMem);

	}

	@Override
	public List adminAuthTopMenuList(String id) {
		return queryForList("AdminMember.adminAuthTopMenuList", id);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.omp.admin.adminmgr.auth.persistence.dao.AdminMemberDAO#adminAuthLeftMenuListMap(java.lang.String,
	 * java.lang.String, java.lang.String)
	 */
	@Override
	public List adminAuthLeftMenuListMap(String id, String topCode, String menuDepth) {
		HashMap map = new HashMap();
		map.put("id", id);
		map.put("topCode", topCode);
		map.put("menuDepth", menuDepth);
		return queryForList("AdminMember.adminAuthLeftMenuListMap", map);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.omp.admin.adminmgr.auth.persistence.dao.AdminMemberDAO#adminAuthLeftMenuListMap(java.lang.String,
	 * java.lang.String, java.lang.String)
	 * 
	 * 운영자 권한 부여 팝업리스트
	 */
	@Override
	public List adminMemberMgrAll(String id, String topCode, String menuDepth) {
		HashMap map = new HashMap();

		if (id.indexOf(',') > 0) {
			map.put("topCode", topCode);
			map.put("menuDepth", menuDepth);
			return queryForList("AdminMember.adminMemberMgrAllDoubleChoice", map);
		} else {
			map.put("id", id);
			map.put("topCode", topCode);
			map.put("menuDepth", menuDepth);
			return queryForList("AdminMember.adminMemberMgrAll", map);
		}
	}

	@Override
	public boolean isAdminValidPageAuth(HashMap map) {
		boolean isValid = false;

		Object obj = queryForObject("AdminMember.adminAuthVaid", map);
		if (obj != null) {
			int cnt = Integer.parseInt((String) obj);
			if (cnt == 1) {
				isValid = true;
			}
		}

		return isValid;
	}

	/**
	 * 로그인 정보 저장
	 */
	@Override
	public void insertLoginInfo(String loginSeq, String mbrId, String accIp, String accDttm) {

		HashMap map = new HashMap();
		map.put("loginSeq", loginSeq);
		map.put("mbrId", mbrId);
		map.put("accIp", accIp);
		map.put("accDttm", accDttm);

		insert("AdminMember.insertLoginInfo", map);
	}

	/**
	 * 고객정보조회 로그 저장
	 */
	@Override
	public void insertIDMSCusInfoLog(HashMap map) {
		map.put("SERVER_IP", getLocalServerIp());// App시스템 IPmap
		OmpLogger.info("insertIDMSCusInfoLog paramMap=" + map);
		insert("AdminMember.insertIDMSCusInfoLog", map);
	}

	/**
	 * 로그인 세션에 저장할 시퀀스번호 조회
	 * */
	@Override
	public String getInsertLoginInfoSeq() throws DaoException {
		return (String) queryForObject("AdminMember.getInsertLoginInfoSeq");
	}

	/**
	 * 관리자 비밀번호 동일 여부 카운트.
	 */
	@Override
	public int getConfirmCountByPassword(HashMap<String, String> map) {
		return (Integer) queryForObject("AdminMember.getConfirmCountByPassword", map);
	}

	@Override
	public void updateAdminPassword(HashMap<String, String> map) {
		update("AdminMember.updateAdminPassword", map);
	}

	@Override
	public void updateLogoutInfo(HashMap<String, String> map) {
		OmpLogger.info("loginSeq paramMap=" + map);
		update("AdminMember.updateLogoutInfo", map);
	}

	/**
	 * 비밀번호 변경 대상 관리자 정보 취득
	 */
	@Override
	public List<AdminMember> getUpdateAdminInfo() {
		return queryForList("AdminMember.getUpdateAdminInfo");
	}

	/**
	 * MD5 해시를 얻는 함수
	 * 
	 * @param data
	 *            MD5해시를 얻기 위한 데이터
	 * @return 생성된 MD5 해시
	 * 
	 */
	private static String getDigestHash(String data) {
		byte[] defaultBytes = data.getBytes();
		String returnVal = "";

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.reset();
			md.update(defaultBytes);
			byte[] md5 = md.digest();

			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < md5.length; i++) {
				hexString.append(Integer.toHexString(0xFF & md5[i]));
			}
			returnVal = hexString.toString();
		} catch (Exception e) {
			OmpLogger.error(e.getMessage(), e);
		}
		return returnVal;
	}

	/**
	 * 회원 리스트를 조회한다.
	 * 
	 * @return
	 */
	@Override
	public List<HashMap<String, String>> getMemberList(HashMap<String, String> param) {
		return queryForList("AdminMember.getMemberList", param);
	}

	/**
	 * 현재 서버의 IP 주소를 가져옵니다.
	 * 
	 * @return IP 주소
	 */
	private String getLocalServerIp() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
		}
		return null;
	}
}
